#!/usr/bin/python
#coding:utf-8
# Author:   --<jamiesun.net@gmail.com>
# Purpose: 
# Created: 2010-01-08

from PyQt4 import QtCore, QtGui
from translatekit import Ui_MainWindow
import translate_api, utils
import sys,service,utils,re,traceback,time


def initlog():
    import logging
    
    logger = logging.getLogger()
    hdlr = logging.FileHandler("coolyee-log.txt")
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.NOTSET)
    return logger

log = initlog()



class MainApp:
    def __init__(self,app):
        self.app = app
        self.mwin = QtGui.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.mwin)
        
        self.mwin.setWindowTitle(u"CoolYee 酷译")
        
        self.initInterface()
        
        self.mwin.showNormal()

        sys.exit(self.app.exec_())
        
    def initInterface(self):
        self.currentid = None
        self.createActions()
        self.createMenus()   
        self.initEvent()
        self.initDictView()
        self.loadTags()
        self.ui.blog.addItems(utils.blogs.keys())
        self.catThread = utils.CategoryThread()
        self.catThread.start()
        self.postWorker = utils.PostThread()
        self.postWorker.start()
   
    def loadTags(self):
        db = service.Store()
        try:
            self.tags = db.getAllTags() or {}
            self.updateTagBox()
        finally:
            db.close()
            
    def updateTagBox(self):
        self.ui.tags.clear()
        self.ui.stags.clear()
        self.ui.tags.addItem("")
        self.ui.tags.addItems(self.tags.keys())
        self.ui.stags.addItems(self.tags.keys())

    def createMenus(self):
        self.docsmenu = QtGui.QMenu(self.ui.doclist)
        self.docsmenu.addAction(self.editDocAct)
        self.docsmenu.addAction(self.rmvDocAct)
        
    def createActions(self):      
        self.editDocAct = QtGui.QAction(("&edit doc"),self.ui.doclist)
        self.editDocAct.setText(u"修改文档")
        QtCore.QObject.connect(self.editDocAct, QtCore.SIGNAL("triggered()"), self.editDoc)
        
        self.rmvDocAct = QtGui.QAction(("&rmove doc"),self.ui.doclist)
        self.rmvDocAct.setText(u"删除文档")
        QtCore.QObject.connect(self.rmvDocAct, QtCore.SIGNAL("triggered()"), self.rmvDoc)
        
    def docContextMenuEvent(self,event):
        sel = self.ui.doclist.currentItem()
        if not sel:
            self.editDocAct.setEnabled(False)
            self.rmvDocAct.setEnabled(False)
        else:
            self.editDocAct.setEnabled(True)
            self.rmvDocAct.setEnabled(True)         
        self.docsmenu.exec_(event.globalPos())
        
    def initEvent(self):
        self.ui.doclist.contextMenuEvent = self.docContextMenuEvent
        QtCore.QObject.connect(self.ui.search, QtCore.SIGNAL("clicked()"), self.queryDocs)
        QtCore.QObject.connect(self.ui.source, QtCore.SIGNAL("textChanged()"), self.dicInputHandler)
        QtCore.QObject.connect(self.ui.transClear, QtCore.SIGNAL("clicked()"), self.transClear)
        QtCore.QObject.connect(self.ui.translate, QtCore.SIGNAL("clicked()"), self.dicTranslate)
        QtCore.QObject.connect(self.ui.langType, QtCore.SIGNAL("clicked()"), self.setLangtype)
        QtCore.QObject.connect(self.ui.tabs, QtCore.SIGNAL("currentChanged(int)"), self.currentChanged)
        QtCore.QObject.connect(self.ui.save, QtCore.SIGNAL("clicked()"), self.saveDoc)
        QtCore.QObject.connect(self.ui.postblog, QtCore.SIGNAL("clicked()"), self.postBlog)
        QtCore.QObject.connect(self.ui.blog, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setBlogCats)
         
        
    def currentChanged(self,idx):
        #idx = self.ui.tabs.currentIndex()
        if idx == 0:
            pass
        elif idx == 1:
            self.queryDocs()
        elif idx == 2:
            pass
        elif idx == 3:
            pass
        else:
            pass
            

    def initDictView(self):
        for it in utils.locs:
            self.ui.langFrom.addItem(it['name'],QtCore.QVariant(it['value']))
            self.ui.langInto.addItem(it['name'],QtCore.QVariant(it['value']))
        self.ui.langFrom.setCurrentIndex(0)
        self.ui.langInto.setCurrentIndex(1)

    def dicInputHandler(self):
        src = self.ui.source.toPlainText()
            
    def dicTranslate(self):
        """"""
        self.dicInputHandler()
        transCall = translate_api.apis[unicode(self.ui.transApi.currentText())]
        srcStr = self.ui.source.toPlainText()
        lfrom = self.ui.langFrom.itemData(self.ui.langFrom.currentIndex()).toString()
        lto = self.ui.langInto.itemData(self.ui.langInto.currentIndex()).toString()
        try:
            reg = re.compile("\n+")
            source = reg.sub("<br>",unicode(srcStr))
            self.ui.dest.clear()
            result = transCall(unicode(lfrom).encode('utf-8'),
                               unicode(lto).encode('utf-8'),
                               source.encode('utf-8'),
                               self.transHandle)
        except Exception,ex:
            QtGui.QMessageBox.warning(self.mwin,u"信息",u"翻译失败",u"关闭") 
            traceback.print_exc() 

    def transHandle(self,result): 
        self.ui.dest.appendHtml(result['content'])

    def transClear(self):
        self.ui.source.clear()
        self.ui.dest.clear()

    def setLangtype(self):
        fidx = self.ui.langFrom.currentIndex()
        tidx = self.ui.langInto.currentIndex()
        self.ui.langFrom.setCurrentIndex(tidx)
        self.ui.langInto.setCurrentIndex(fidx)
                  
    
    def postBlog(self):
        if not self.ui.content.toPlainText():
            return
        def getTitle(ct):
            end = ct.indexOf("\n")
            return ct[0:end]
        blog = {}
        blog['title'] = unicode(getTitle(self.ui.content.toPlainText()))
        blog['blogname'] = unicode(self.ui.blog.currentText())
        if blog['blogname'] == u"博客":
            QtGui.QMessageBox.warning(self.mwin,u"信息",u"请选择博客",u"关闭") 
            return
        blog['desc'] = unicode(self.ui.content.toPlainText().replace("\n","<br>"))
        blog['tag'] = unicode(self.ui.stags.currentText())
        blog['categories'] = unicode(self.ui.blogCategories.currentText())
        if blog['categories'] == u"分类":
            QtGui.QMessageBox.warning(self.mwin,u"信息",u"请选择分类",u"关闭")
            return
        self.postWorker.addBlog(blog)


    def blogPostHandle(self,s):
        QtGui.QMessageBox.information(self.mwin,u"信息",s)
           
    def setBlogCats(self,blogname):
        self.ui.blogCategories.clear()
        self.ui.blogCategories.addItems(utils.categories[str(blogname.toUtf8())])    


    def queryDocs(self):
        q = self.ui.keyword.text()
        tag = self.ui.tags.currentText()
        db = service.Store()
        try:
            self.ui.doclist.clear()
            docs = db.getAll(service.DOC_DB,tag,q)
            if docs:
                for doc in docs:
                    item =  QtGui.QListWidgetItem(QtGui.QIcon(":/tkit/icon/51.ico"),doc.title,self.ui.doclist)
                    item.doc_data = doc     
        finally:
            db.close()
                                
    def saveDoc(self):
        if not self.ui.content.toPlainText():
            return
        def getTitle(ct):
            end = ct.indexOf("\n")
            return ct[0:end]
        db = service.Store()
        try:
            #处理文档
            doc = service.Doc()
            doc.id = self.currentid
            doc.title = unicode(getTitle(self.ui.content.toPlainText()))
            doc.tag = unicode(self.ui.stags.currentText())
            doc.content = unicode(self.ui.content.toPlainText() or "")
            doc.datetime = time.strftime(u'%Y-%m-%d %H:%M:%S', time.gmtime())
            self.currentid = doc.id
            #处理标签
            itag = db.getTag(doc.tag)
            if not itag:
                itag = service.Tag()
                itag.name = doc.tag
                itag.count = 1
            else:
                itag.count +=1
                
            self.tags[itag.name] = itag
            db.addDoc(doc)
            db.setTag(itag)
        finally:
            db.close()
        self.updateTagBox()
        QtGui.QMessageBox.information(self.mwin,u"信息",u"保存成功")

    def editDoc(self):
        item = self.ui.doclist.currentItem()
        if not item or not item.doc_data:
            return
        self.currentid = item.doc_data.id
        self.ui.content.setPlainText(item.doc_data.content) 
        self.ui.stags.addItem(item.doc_data.tag)
        self.ui.tabs.setCurrentIndex(0)

        
    def rmvDoc(self):
        item = self.ui.doclist.currentItem()
        if item and item.doc_data:
            cfm = QtGui.QMessageBox.question(self.mwin,u"询问",u"您确定删除吗？",QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
            if cfm == QtGui.QMessageBox.Yes:
                db = service.Store()
                rs = False
                try:rs = db.removeDoc(item.doc_data.id)
                finally:db.close() 
                if rs:self.queryDocs()

    

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mainApp = MainApp(app)
    